%% segment data

n_frames = 300;
params = {};



% the parameters
params.meanoverdeltaT= 5;
params.sigma=1;
params.deltaT=2;
params.vol_thres=100;
params.overlap=.5;
params.corrthres = .5;
params.medianfilt = 1;
params.medianfitlSize = 3;
params.t_factor=6;
stop = floor(size(data{1},3)/n_frames);
%%

allRois = false([400 750 400]);
nrois  = 0;

for i = 1:5
    [r,diffdata] = difference_segmentation(data{1}(:,:,(i-1)*n_frames+1:i*n_frames,params);
    r=mergin_correlation(diffdata,r,params.corrthres);
    nNew = size(r,3);
    allRois(:,:,nrois+1:nrois+nNew)=r;
    nrois = nrois +nNew;
end

[b,rs]=segmentMerging(nrois,allRois(:,:,1>nrois),.5);

%%plot manual rois and segmented rois side by side

%      for nM=1:numel(i)
%          s=sprintf('Merged %d with %d',i(nM),j(nM));
%          disp(s)
%          figure(30+nM)
%          subplot(211)
%          plot(1:numel(averageTraces(:,i(nM))),averageTraces(:,i(nM)),'r', ...
%              1:numel(averageTraces(:,j(nM))),averageTraces(:,j(nM)),'g')
%          legend(sprintf('Segment %d',i(nM)),sprintf('Segmentd %d',j(nM)))
%          subplot(212)
%          ov=imoverlay(meanIm,bwperim(binxymask(:,:,i(nM))),[0,255,255]);
%          imshow(ov);
%      end